/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-02-27 11:14:11
 */
import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators'
import store from '@/store'
import { isNil, clone } from 'ramda'
import { AdminUserInfo } from '@/interfaces/user.dto'

export interface AppState {
	collapsed: boolean // 左边导航栏关闭状态
	userInfo: AdminUserInfo
}
@Module({ store, name: 'app', namespaced: true, dynamic: true })
class App extends VuexModule implements AppState {
	public collapsed = false
	public userInfo: AdminUserInfo = {}
	@Action
	public toggleCollapsed() {
		this.TOGGLE_COLLAPSED(!this.collapsed)
	}
	@Action
	public async getUserInfo() {
		const userNo = localStorage.getItem('userId')
		if (!isNil(userNo)) {
			const { success, data } = await API.server.adminUser.getUserInfo.request({ id: Number(userNo) })
			if (success && !isNil(data)) {
				this.GET_USERINFO(data)
			}
			return data
		}
		return null
	}
	@Action
	public async setUserInfo(data: any) {
		this.GET_USERINFO(data)
	}
	@Mutation
	private TOGGLE_COLLAPSED(collapsed: boolean) {
		this.collapsed = collapsed
	}
	@Mutation
	private GET_USERINFO(userInfo: AdminUserInfo) {
		this.userInfo = clone(userInfo)
	}
	@Mutation
	private CLEAR_USER_CACHE() {
		localStorage.removeItem('accessToken')
		localStorage.removeItem('userNo')
		location.href = '/login'
	}
	@Action
	public async userLogout() {
		this.CLEAR_USER_CACHE()
		return false
	}
}
export const AppModule = getModule(App)
